import { useEffect, useRef, useState } from 'react';
import { Button, message, Avatar, Popconfirm, Card } from 'antd';
import { history } from 'umi';
import moment from 'moment';
import { ArrowLeftOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { ProTable } from '@ant-design/pro-components';
import {
  queryKnowledgeListById,
  deleteDataKnowledge,
  queryKnowledgeDetail,
  deleteKnowledge,
} from '@/services/knowledge';
import AddKnowledgeModel from '../../components/addKnowledgeModel/index';
import KnowledgeDetailModel from '../../components/knowledgeDetailModel/index';
import ManagerModel from '../../components/managerModel/index';

import type { ProColumns } from '@ant-design/pro-table';
import type { ActionType, ParamsType } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';

import useDetailType from '@/hooks/useDetailType';

import styles from './style.less';
import { isEmpty } from 'lodash';

const enumRecord = {
  PDF: '上传文档',
  TEXT: '在线编辑',
  WORD: '导入链接',
};

const KnowledgeDataList: React.FC = () => {
  const { goBack, params } = useDetailType<Partial<{ id: string }>>();
  const { id } = params;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  // const [btnLoading, setbtnLoading] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [managerVisible, setManagerVisible] = useState(false);
  const [knowledgeVisible, setKnowledgeVisible] = useState(false);
  const [modelTitle, setModelTitle] = useState('');
  const [modelItem, setModelItem] = useState(null);
  const [knowledgeDetailInfo, setKnowledgeDetailInfo] = useState<API.KnowledgeDetail>();

  const pageQueryComing = async () => {
    if (id) {
      const res = await queryKnowledgeDetail({ id: id });
      if (!res.code && res.data) {
        setKnowledgeDetailInfo(res.data);
      }
    }
  };

  useEffect(() => {
    pageQueryComing();
  }, []);

  // 替换知识文档
  const replaceItem = async (record: any) => {
    const itemModel: any = { id: id };
    setAddVisible(true);
    setModelItem(itemModel);
    setModelTitle(enumRecord[record.type]);
  };

  // 删除知识文档
  const deleteItem = async (idItem: number) => {
    const res = await deleteDataKnowledge({ id: idItem });
    if (!res.code && res.data) {
      message.success('删除成功');
      actionRef?.current?.reloadAndRest?.();
    }
  };

  // 去详情
  const lookItem = async (idItem: number) => {
    history.push(`/knowledge/data/detail/edit/${idItem}`);
  };

  // table-列
  const columns: ProColumns<API.KnowledgeListItemById>[] = [
    {
      title: '关键字',
      dataIndex: 'linkId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请选输入标题、关键字',
      },
    },
    {
      title: '文档名称',
      dataIndex: 'title',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '来源',
      dataIndex: 'type',
      align: 'center',
      valueEnum: {
        PDF: '上传文档',
        TEXT: '在线编辑',
        WORD: '导入链接',
      },
      hideInSearch: true,
    },
    // {
    //   title: '创建人',
    //   dataIndex: '',
    //   align: 'center',
    //   hideInSearch: true,
    // },
    {
      title: '最后更新时间',
      dataIndex: 'updatedAt',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        const { updatedAt } = record;
        return updatedAt ? moment(updatedAt).format('YYYY-MM-DD HH:mm:ss') : '-';
        // return updatedAt ? `${updatedAt?.split('.')[0]}` : '-';
      },
    },
    {
      title: '操作',
      width: 400,
      valueType: 'option',
      dataIndex: 'option',
      align: 'center',
      render: (text, record) => [
        <a
          key="view"
          onClick={() => {
            lookItem(record.id);
          }}
        >
          详情
        </a>,
        <a
          key="replace"
          onClick={() => {
            replaceItem(record);
          }}
        >
          替换
        </a>,
        // <a
        //   key="author"
        //   onClick={() => {
        //     setManagerVisible(true);
        //   }}
        // >
        //   权限
        // </a>,
        <Popconfirm
          key="delete"
          title={`确认删除文档${record.title}？`}
          onConfirm={() => deleteItem(record.id)}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  // 列表查询
  const queryListById = async (paramsTable: ParamsType) => {
    const { current } = paramsTable;
    const param: API.BasePagination & { id: number } = {
      pageNum: current || 1,
      pageSize: paramsTable.pageSize || 10,
      id: Number(id),
    };

    const res = await queryKnowledgeListById({ id: param.id });
    if (!res.code && res.data) {
      const { records, total, size } = res.data;
      return {
        total: total,
        pageSize: size,
        current: res.data.current,
        data: records,
      };
    }
    return [];
  };

  //打开新增知识库弹窗--分三种
  const openAddModel = (item: any, nameType: string) => {
    setAddVisible(true);
    setModelItem(item);
    setModelTitle(nameType);
  };

  const toDeleteKnowledge = async (ids: string) => {
    const res = await deleteKnowledge({ id: ids });
    if (!res.code && res.data) {
      message.success('删除成功');
      goBack();
    }
  };

  // const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  return (
    <div className={styles.container}>
      <Card
        title={
          <h3>
            <ArrowLeftOutlined className={styles['title-icon']} onClick={goBack} />
            知识库文档
          </h3>
        }
        bodyStyle={{ display: 'none' }}
      />

      <div className={styles['list-body']}>
        <div className={styles['list-body-left']}>
          <ProTable<API.KnowledgeListItemById>
            rowKey="id"
            columns={columns}
            actionRef={actionRef}
            formRef={formRef}
            //@ts-ignore
            request={queryListById}
            options={false}
            scroll={{ x: 800 }}
            // pagination={{
            //   showSizeChanger: true,
            //   size: 'small',
            //   showTotal,
            //   showQuickJumper: true,
            // }}
            toolBarRender={() => [
              <Button
                key="button"
                type="primary"
                onClick={() => openAddModel({ id: id }, '上传文档')}
              >
                上传文档
              </Button>,
              <Button
                key="button"
                type="primary"
                onClick={() => openAddModel({ id: id }, '在线编辑')}
              >
                在线编辑
              </Button>,
              <Button
                key="button"
                type="primary"
                onClick={() => openAddModel({ id: id }, '导入链接')}
              >
                导入链接
              </Button>,
            ]}
          />
        </div>

        <div className={styles['list-body-right']}>
          <div className={styles['right-title']}>
            {knowledgeDetailInfo?.name}
            <Popconfirm
              key="delete"
              title={`确认删除知识库${knowledgeDetailInfo?.name}？`}
              onConfirm={() => toDeleteKnowledge(knowledgeDetailInfo?.id || '')}
            >
              <DeleteOutlined />
            </Popconfirm>
          </div>
          <div className={styles['right-time']}>
            创建时间：
            {knowledgeDetailInfo?.createdAt
              ? moment(knowledgeDetailInfo.createdAt).format('MM月DD日 HH:mm')
              : '-'}
          </div>
          <div className={styles['right-time']}>
            {isEmpty(knowledgeDetailInfo?.description)
              ? '暂无描述'
              : '描述说明:' + knowledgeDetailInfo?.description}
            <EditOutlined onClick={() => setKnowledgeVisible(true)} />
          </div>

          <div className={styles['right-peoples']} onClick={() => setManagerVisible(true)}>
            所有人：
            {knowledgeDetailInfo?.owner || '-'}
          </div>

          <div className={styles['right-peoples']} onClick={() => setManagerVisible(true)}>
            管理员：
            <EditOutlined />
            {knowledgeDetailInfo?.managerList?.map((item: any) => {
              return (
                <div style={{ marginBottom: '4px' }} key={item.name}>
                  <Avatar size="small" src={item.avatar} />
                  <span style={{ marginLeft: '6px' }}>{item.username}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* 新增弹窗 */}
      <AddKnowledgeModel
        addVisible={addVisible}
        modelTitle={modelTitle}
        modelItem={modelItem}
        closeModel={() => {
          setAddVisible(false);
          actionRef?.current?.reloadAndRest?.();
        }}
        type="edit"
      />

      {/* 关联管理员弹窗 */}
      <ManagerModel
        managerVisible={managerVisible}
        managerId={id || ''}
        managerTitle="关联管理员"
        closeModel={() => {
          pageQueryComing();
          setManagerVisible(false);
        }}
      />

      {/* 编辑知识库--弹窗 */}
      <KnowledgeDetailModel
        knowledgeVisible={knowledgeVisible}
        knowledgeDetailInfo={knowledgeDetailInfo}
        modelTitle="基础信息管理"
        closeModel={() => {
          pageQueryComing();
          setKnowledgeVisible(false);
        }}
      />
    </div>
  );
};

export default KnowledgeDataList;
